import { computed, h, reactive, ref } from 'vue';
import { FormRules, NAvatar, NButton, NSpace, NTag } from 'naive-ui';
import { Layer } from 'slash-layer';
import form from './AuthTbUserUpdate.vue';
import httpApi from './httpApi';
import { AuthTbRoleApi } from '@/views/AuthTbRole';
import { AuthTbDeptApi } from '@/views/AuthTbDept';
import { MyTableBasicColumn, SlashAppContext, checkAuthShow } from 'slash-admin';
import { AuthTbPostApi } from '@/views/AuthTbPost';
import UserBindDataSecurity from '@/views/AuthTbUser/UserBindDataSecurity/UserBindDataSecurity.vue';
import { AuthCodes } from '@/apis/auth-code';
import BatchUserConfig from './BatchUserConfig.vue';
import Utils from '@/utils';

/**
 * 视图控制
 */
export const vCtl = reactive({
  addBtn: computed(() => {
    return true;
  }),
  updateBtn: computed(() => {
    return true && checkedRows.value.length == 1;
  }),
  delBtn: computed(() => {
    return true && checkedRows.value.length >= 1;
  }),
});
export const initQuery = {};
export const queryForm = ref<any>(JSON.parse(JSON.stringify(initQuery)));
export const tableRef = ref<any>();

export function reloadTable() {
  if (tableRef.value) {
    setTimeout(() => {
      tableRef.value.reload();
    }, 50);
  }
}

/**
 * 选中的数据
 */
export const checkedRows = ref<any>([]);

/**
 * 选中行
 * @param rows
 */
export async function onCheckedRowEvent(rows: any[]) {
  checkedRows.value = rows;
}

export const asyncApi = (api: () => Promise<any>) => {
  let obj = ref<any>();
  api().then((msg) => {
    obj.value = msg;
  });
  return obj;
};
export const getRoleOptions = async () => {
  const { data } = await AuthTbRoleApi.selectList({});
  const result = data.map((it) => {
    return {
      value: it.roleCode,
      label: it.roleName,
    };
  });
  return result;
};
export const getPostOptions = async () => {
  const { data } = await AuthTbPostApi.selectList({});
  const result = data.map((it) => {
    return {
      value: it.id,
      label: it.postName,
    };
  });
  console.log('PostOptions', result);
  return result;
};
export const getDeptOptions = async () => {
  const { data } = await AuthTbDeptApi.selectTreeList();
  const result = data;
  console.log('DeptOptions', result);
  return result;
};

// export const accountTypeOptions = asyncApi(async () => {
//     const {data} = await SysTbDictApi.selectList({});
//     const result = data.map(it => {
//         return {
//             value: it.roleCode, label: it.roleName
//         }
//     })
//     console.log("哈哈", result);
//     return result;
// })
/**
 * 枚举字段
 */
export const enabledTextEnum = reactive({
  1: {
    text: '启用',
    style: 'info',
  },
  0: {
    text: '禁用',
    style: 'error',
  },
});
/**
 * 枚举字段
 */
export const isLockTextEnum = reactive({
  1: {
    text: '锁定',
    style: 'error',
  },
  0: {
    text: '正常',
    style: 'info',
  },
});
/**
 * 枚举字段
 */
export const sexTextEnum = reactive({
  1: {
    text: '男',
    style: 'info',
  },
  2: {
    text: '女',
    style: 'error',
  },
  0: {
    text: '未知',
    style: 'default',
  },
});
export const getEnabledTextEnum = (key: number | string) => {
  return enabledTextEnum[key].text || `--`;
};

export const getEnabledStyleEnum = (key: number | string) => {
  return enabledTextEnum[key].style || `--`;
};
export const enabledOptions = computed(() => {
  const temp: any = [];
  Object.keys(enabledTextEnum).forEach(function (key: any) {
    temp.push({
      value: parseInt(key),
      label: enabledTextEnum[key].text,
    });
  });
  return temp.reverse();
});

export const sexOptions = computed(() => {
  const temp: any = [];
  Object.keys(sexTextEnum).forEach(function (key: any) {
    temp.push({
      value: parseInt(key),
      label: sexTextEnum[key].text,
    });
  });
  return temp;
});
export const isLockOptions = computed(() => {
  const temp: any = [];
  Object.keys(isLockTextEnum).forEach(function (key: any) {
    temp.push({
      value: parseInt(key),
      label: isLockTextEnum[key].text,
    });
  });
  return temp.reverse();
});

/**
 * 更新弹框
 * @param row
 */
export async function doUpdateModal(row: any) {
  if (checkedRows.value.length != 1 && !row) {
    Layer.error('请选择数据条目后操作');
    return;
  }
  if (!row) {
    row = {
      id: checkedRows.value[0],
    };
  }
  await Layer.updateForm({
    title: '编辑用户',
    content: {
      component: form,
      props: { ...row },
    },
  } as any);
  await reloadTable();
}

/**
 * 更新弹框
 * @param row
 */
export async function doBindDataSecurityModal(row: any) {
  if (checkedRows.value.length === 0 && !row) {
    Layer.error('请选择数据条目后操作');
    return;
  }
  if (!row) {
    row = {
      id: checkedRows.value,
    };
  }

  await Layer.updateForm({
    title: '数据授权',
    position: 'lg',
    content: {
      component: UserBindDataSecurity,
      props: { ...row },
    },
  } as any);
  await reloadTable();
}

/**
 * 批量配置用户信息
 * @param row
 */
export async function doBatchConfigUserInfo() {
  if (checkedRows.value.length === 0) {
    Layer.error('请选择数据条目后操作');
    return;
  }

  await Layer.updateForm({
    title: '批量配置用户信息',
    position: 'md',
    content: {
      component: BatchUserConfig,
      props: { id: checkedRows.value },
    },
  } as any);
  await reloadTable();
}

/**
 * 新增
 * @param row
 */
export async function doSaveModal(row: any) {
  console.log('传递的数据:{}', row);
  await Layer.createForm({
    title: '新建用户',
    content: {
      component: form,
      props: {},
    },
  } as any);
  await reloadTable();
}

/**
 * 删除
 * @param row
 */
export async function doDeleteModal(row: any) {
  let ids: any = [];
  if (!row) {
    ids = [...checkedRows.value];
  }
  if (row) {
    ids.push(row.id);
  }

  if (ids.length == 0) {
    Layer.error('请选择要删除的数据条目');
    return;
  }
  await Layer.confirm('您确定删除选中记录么');
  await httpApi.doLogicDeleteEntity(ids);
  await reloadTable();
}

/**
 * 查看表单
 * @param row
 */
export async function doReadModal(row: any) {
  if (checkedRows.value.length != 1 && !row) {
    Layer.error('请选择数据条目后操作');
    return;
  }
  if (!row) {
    row = {
      id: checkedRows.value[0],
    };
  }
  await Layer.readForm({
    title: '编辑',
    content: {
      component: form,
      props: { ...row },
    },
  } as any);
  await reloadTable();
}
/**
 * 列表页面列
 */
export const tableColumns: MyTableBasicColumn[] = [
  {
    title: '选中',
    key: 'id',
    type: 'selection',
    fixed: 'left',
    width: 50,
    disabled(row: any) {
      return row.name === 'Edward King 3';
    },
  },
  {
    title: '头像',
    key: 'headImgAddress',
    // sorter: "headImgAddress",
    width: 60,
    render: function (row: any) {
      let src = '';
      let title = row.username.substring(0, 1);
      if (row.headImgAddress) {
        src = SlashAppContext.fileBaseUrl() + row.headImgAddress;
      }
      return h(
        NAvatar,
        {
          round: true,
          style: {
            color: 'white',
            backgroundColor: '#97CBFF',
          },
          src: SlashAppContext.fileBaseUrl() + row.headImgAddress,
          fallbackSrc: Utils.getImageUrl('errorImgWhite.png'),
        },
        src ? '' : title
      );
    },
  },
  {
    title: '账号',
    key: 'account',
    sorter: 'account',
    width: 120,
  },
  {
    title: '昵称',
    key: 'nickName',
    sorter: 'nickName',
    width: 120,
  },
  {
    title: '姓名',
    key: 'username',
    sorter: 'username',
    searchType: 'like',
    width: 120,
    searchProps: {
      type: 'text',
    },
  },
  {
    title: '电话',
    key: 'phone',
    sorter: 'phone',
    searchType: 'like',
    width: 150,
    searchProps: {
      type: 'text',
    },
  },
  {
    title: '账号',
    key: 'account',
    show: false,
    width: 150,
    searchType: 'like',
    searchProps: {
      type: 'text',
    },
  },
  // {
  //   title: '邮箱',
  //   key: 'email',
  //   sorter: 'email',
  //   width: 150,
  // },
  // {
  //   title: '性别',
  //   key: 'sex',
  //   sorter: 'sex',
  //   width: 80,
  //   render(row: any) {
  //     return h(
  //       NTag,
  //       {
  //         type: sexTextEnum[row.sex].style,
  //       },
  //       sexTextEnum[row.sex].text
  //     );
  //   },
  // },
  /*  {
    title: '状态',
    key: 'isLock',
    sorter: 'isLock',
    width: 80,
    render(row: any) {
      return h(
        NTag,
        {
          type: isLockTextEnum[row.isLock].style,
        },
        isLockTextEnum[row.isLock].text
      );
    },
  }, */
  {
    title: '角色',
    key: 'authTbRoleList',
    searchKey: 'fkRoleCode',
    width: 160,
    render(row: any) {
      if (!row.authTbRoleList) return '';
      let tagList = row.authTbRoleList.map((it) => {
        return h(
          NTag,
          {
            type: 'info',
          },
          it.roleName
        );
      });
      return h(NSpace, tagList);
    },
    searchProps: {
      type: 'select',
    },
  },

  {
    title: '账号状态',
    key: 'isLock',
    width: 100,
    render(row: any) {
      return h(
        NTag,
        {
          type: isLockTextEnum[row.isLock] ? isLockTextEnum[row.isLock].style : 'info',
        },
        isLockTextEnum[row.isLock] ? isLockTextEnum[row.isLock].text : '未知'
      );
    },
    searchProps: {
      type: 'select',
    },
  },
  {
    title: '账号类型',
    key: 'accountType',
    width: 150,
  },
  {
    title: '创建时间',
    key: 'createTime',
    show: false,
    width: 120,
    searchProps: {
      type: 'date-range',
    },
  },

  {
    title: '操作',
    key: 'action',
    type: 'id',
    fixed: 'right',
    width: 200 * SlashAppContext.getCoefficient(),
    render: function (row: any) {
      const arr = [
        h(
          NButton,
          {
            onVnodeMounted: async (vNode) => {
              await checkAuthShow(vNode.el as any, AuthCodes['用户管理数据授权']);
            },
            type: 'primary',
            text: true,
            onClick: (async (row: any) => {
              await doBindDataSecurityModal(row);
            }).bind(null, row),
          },
          '数据授权'
        ),
        h(
          NButton,
          {
            onVnodeMounted: async (vNode) => {
              await checkAuthShow(vNode.el as any, AuthCodes['用户管理编辑']);
            },
            type: 'primary',
            text: true,
            onClick: (async (row: any) => {
              await doUpdateModal(row);
            }).bind(null, row),
          },
          '编辑'
        ),
        h(
          NButton,
          {
            onVnodeMounted: async (vNode) => {
              await checkAuthShow(vNode.el as any, AuthCodes['用户管理删除']);
            },
            type: 'primary',
            text: true,
            onClick: (async (row: any) => {
              await doDeleteModal(row);
            }).bind(null, row),
          },
          '删除'
        ),
      ];
      if (!row.isLock) {
        arr.unshift(
          h(
            NButton,
            {
              onVnodeMounted: async (vNode) => {
                await checkAuthShow(vNode.el as any, AuthCodes['用户管理解锁']);
              },
              type: 'primary',
              text: true,
              onClick: (async (row: any) => {
                const res = await httpApi.doUnlockUser([row.id]);
                if (res.code == 200) {
                  Layer.success('解锁成功');
                } else {
                  Layer.error('解锁失败');
                }
                await reloadTable();
              }).bind(null, row),
            },
            '解锁'
          )
        );
      }
      return h(NSpace, arr);
    },
  },
];
/**
 * 新增和更新校验规则
 */
export const formRules = reactive<FormRules>({
  nickName: [
    {
      required: true,
      validator: (rule, val) => Utils.validSpace(rule, val, '请输入昵称'),
      trigger: 'blur',
    },
  ],
  username: [
    {
      required: true,
      validator: (rule, val) => Utils.validSpace(rule, val, '请输入姓名'),
      trigger: 'blur',
    },
  ],
  phone: [
    {
      required: true,
      validator: (rule, val) => Utils.validSpace(rule, val, '请输入电话'),
      trigger: 'blur',
    },
  ],
  account: [
    {
      required: true,
      validator: (rule, val) => Utils.validSpace(rule, val, '请输入账号'),
      trigger: 'blur',
    },
  ],
});

/** 数据权限 */
export async function getAllDataPermission(searchKey: string) {
  const dataObjMap: any[] = [];
  const dataFieldMap = new Map();
  const res = await httpApi.fetchAllDataPermssion(searchKey);
  if (res.code == 200) {
    res.data.forEach((obj: any) => {
      // 存权限对象
      if (!obj.label) obj.label = obj.dataSecurityName;
      dataObjMap.push(obj);
      // 存权限字段
      if (obj.children?.length) {
        // obj.children.forEach((child: any) => {
        //   child.group && dataFieldMap.set(obj.tableName, child)
        // })
        dataFieldMap.set(obj.unId, obj.children);
      }
    });
  }
  return {
    dataObjMap,
    dataFieldMap,
  };
}
